package com.foodapp.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foodapp.back.dto.DishDTO;
import com.foodapp.back.entity.Dish;
import com.foodapp.back.entity.Restaurant;
import com.foodapp.back.exception.ApiException;
import com.foodapp.back.mapper.DishMapper;
import com.foodapp.back.service.DishService;
import com.foodapp.back.service.RestaurantService;
import com.foodapp.back.vo.DishVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品服务实现类
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private RestaurantService restaurantService;

    @Override
    public Page<DishVO> pageList(Integer page, Integer size, Long restaurantId, String category, String keyword) {
        Page<Dish> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        
        // 查询条件
        if (restaurantId != null) {
            wrapper.eq(Dish::getRestaurantId, restaurantId);
        }
        
        if (StringUtils.isNotBlank(category)) {
            wrapper.eq(Dish::getCategory, category);
        }
        
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(Dish::getName, keyword)
                    .or().like(Dish::getDescription, keyword);
        }
        
        // 按销量降序排序
        wrapper.orderByDesc(Dish::getSales);
        
        // 查询分页数据
        Page<Dish> dishPage = page(pageParam, wrapper);
        
        // 转换为VO
        Page<DishVO> result = new Page<>();
        BeanUtils.copyProperties(dishPage, result, "records");
        
        List<DishVO> dishVOList = dishPage.getRecords().stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            
            // 获取餐厅名称
            Restaurant restaurant = restaurantService.getById(dish.getRestaurantId());
            if (restaurant != null) {
                dishVO.setRestaurantName(restaurant.getName());
            }
            
            return dishVO;
        }).collect(Collectors.toList());
        
        result.setRecords(dishVOList);
        
        return result;
    }

    @Override
    public List<DishVO> getMenuByRestaurantId(Long restaurantId) {
        // 校验餐厅是否存在
        Restaurant restaurant = restaurantService.getById(restaurantId);
        if (restaurant == null) {
            throw new ApiException("餐厅不存在");
        }
        
        // 查询菜品列表
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getRestaurantId, restaurantId)
                .eq(Dish::getStatus, 1) // 只查询上架的菜品
                .orderByDesc(Dish::getSales);
        
        List<Dish> dishList = list(wrapper);
        
        // 转换为VO
        return dishList.stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setRestaurantName(restaurant.getName());
            return dishVO;
        }).collect(Collectors.toList());
    }

    @Override
    public DishVO getDishById(Long id) {
        Dish dish = getById(id);
        if (dish == null) {
            throw new ApiException("菜品不存在");
        }
        
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        
        // 获取餐厅名称
        Restaurant restaurant = restaurantService.getById(dish.getRestaurantId());
        if (restaurant != null) {
            dishVO.setRestaurantName(restaurant.getName());
        }
        
        return dishVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDish(DishDTO dishDTO) {
        // 校验餐厅是否存在
        Restaurant restaurant = restaurantService.getById(dishDTO.getRestaurantId());
        if (restaurant == null) {
            throw new ApiException("餐厅不存在");
        }
        
        // 创建菜品实体
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        
        // 设置初始值
        dish.setSales(0);
        dish.setStatus(dishDTO.getStatus() != null ? dishDTO.getStatus() : 1);
        dish.setIsDeleted(0);
        
        return save(dish);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDish(DishDTO dishDTO) {
        // 校验菜品是否存在
        Dish dish = getById(dishDTO.getId());
        if (dish == null) {
            throw new ApiException("菜品不存在");
        }
        
        // 校验餐厅是否存在
        Restaurant restaurant = restaurantService.getById(dishDTO.getRestaurantId());
        if (restaurant == null) {
            throw new ApiException("餐厅不存在");
        }
        
        // 更新菜品信息
        BeanUtils.copyProperties(dishDTO, dish);
        
        return updateById(dish);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDish(Long id) {
        // 校验菜品是否存在
        Dish dish = getById(id);
        if (dish == null) {
            throw new ApiException("菜品不存在");
        }
        
        // 逻辑删除
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status) {
        // 校验菜品是否存在
        Dish dish = getById(id);
        if (dish == null) {
            throw new ApiException("菜品不存在");
        }
        
        // 更新状态
        dish.setStatus(status);
        
        return updateById(dish);
    }
}
